package com.killcalorie.wjduan


import com.killcalorie.wjduan.auth.dto.ApiResponse   
import com.killcalorie.wjduan.auth.dto.SignUpRequest
import com.killcalorie.wjduan.auth.dto.LoginRequest


import com.killcalorie.wjduan.auth.dto.AuthenticationRequest
import com.killcalorie.wjduan.message.Message


import com.killcalorie.wjduan.auth.dto.AuthenticationResponse


import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.web.client.TestRestTemplate
import org.springframework.boot.test.web.server.LocalServerPort

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*
import org.springframework.test.context.ActiveProfiles


import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlin.test.assertNotNull


import org.slf4j.LoggerFactory




@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class WjduanApplicationTests {

    private val logger = LoggerFactory.getLogger(WjduanApplicationTests::class.java)


    @LocalServerPort
    private var port: Int = 0

    @Autowired
    private lateinit var restTemplate: TestRestTemplate

 	// 定义函数

	private val baseUrl: String get() = "http://localhost:$port"
    private val email : String get() = "testuser@email.com"
    private val right_password : String get() = "password"
    private val wrong_password : String get() = "wrong_password"

	@Test
	fun contextLoads() {
	
	}

    @Test
    fun `full authentication flow should work`() {
        // 1. 注册新用户

        val registerRequest = SignUpRequest(email=email, password=right_password)
        val registerResponse = restTemplate.postForEntity(
            "${baseUrl}/api/auth/signup",
            registerRequest,
            ApiResponse::class.java
        )
        assertEquals(HttpStatus.OK, registerResponse.statusCode)
        assertTrue(registerResponse.body?.success ?: false)

        // 2. 登录获取令牌
        val loginRequest = LoginRequest(email=email, password=right_password)
        val loginResponse = restTemplate.postForEntity(
            "${baseUrl}/api/auth/signin",
            loginRequest,
            ApiResponse::class.java
        )
        
        assertEquals(HttpStatus.OK, loginResponse.statusCode)
        println("loginResponse Request Headers: ${loginResponse.headers}")


        val token = loginResponse.headers?.getFirst(HttpHeaders.AUTHORIZATION)
        assertNotNull(token, "Token not found in response headers")

        // 3. 使用令牌访问受保护资源
        val headers = HttpHeaders().apply {
            set(HttpHeaders.AUTHORIZATION, token)
        }


        println("dwj ${token}")
        
        // 创建消息
        val messageRequest = Message("Testmessage")
        val createResponse = restTemplate.exchange(
            "${baseUrl}/api/message/putmessage",
            HttpMethod.POST,
            HttpEntity(messageRequest, headers),
            Message::class.java
        )


        assertEquals(HttpStatus.OK, createResponse.statusCode)
        assertNotNull(createResponse.body?.id)
        assertEquals("Testmessage", createResponse.body?.text)


        val id = createResponse.body?.id

        // 4. 获取消息列表
        val getResponse = restTemplate.exchange(
            "${baseUrl}/api/message/getmessage/${id}",
            HttpMethod.GET,
            HttpEntity(null, headers),
            Message::class.java
        )
        assertEquals(HttpStatus.OK, getResponse.statusCode)

        // 5. 登出
        val logoutResponse = restTemplate.exchange(
            "${baseUrl}/api/auth/logout",
            HttpMethod.POST,
            HttpEntity(null, headers),
            String::class.java
        )
        
        assertEquals(HttpStatus.OK, logoutResponse.statusCode)
        // assertEquals("Logged out successfully.", logoutResponse.body)
    }

    // @Test
    // fun `should reject invalid authenticate`() {
    //     val loginRequest = AuthenticationRequest(email, wrong_password)
    //     val loginResponse = restTemplate.postForEntity(
    //         "${baseUrl}/api/auth/authenticate",
    //         loginRequest,
    //         ApiResponse::class.java
    //     )
        
    //     assertEquals(HttpStatus.BAD_REQUEST, loginResponse.statusCode)
    //     assertNotNull(loginResponse.body?.message)
    // }

    // @Test
    // fun `should reject unauthenticated access to protected resources`() {
    //     val response = restTemplate.getForEntity(
    //         "${baseUrl}/api/messages",
    //         String::class.java
    //     )
        
    //     assertEquals(HttpStatus.UNAUTHORIZED, response.statusCode)
    // }
}